<?php

namespace Frieza\Modules\CommunityMcn\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Doraemon\model\CommunityMcn\GoodsRecommender as mGoodsRecommender;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class RecommenderInfoController extends Controller
{

    const CONTENT_PARAM_LIST = [
        'join_type' => '参与方式',
        'content_range' => '内容范围',
        'word_require' => '文字要求',
        'pic_require' => '图片要求',
        'goods_relation' => '商品关联',
    ];

    public function create(Content $content, $id = 0)
    {
        $formatInfo = [];
        if ($id) {
            $info = mGoodsRecommender::getById($id);
            $formatInfo = self::formatInfo($info);
            $formatInfo['user_profile'] = AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_RECOMMENDER, true);
        }
        $form = new Form($formatInfo);
        $form->hidden('id', 'ID');
        $form->text('title', '活动名称')->required();
        $form->imgUpload('pic_id', '活动头图', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->dateRange('start_time', 'end_time', '活动时间')->required();
        $form->text('activity_tag', '活动标签')->required();
        $form->radioButton('reward_type', '奖励类型')->options(mGoodsRecommender::REWARD_TYPE_LIST)
            ->when('=', mGoodsRecommender::TYPE_POINT, function ($form) {
                $form->text('point_first', '积分分值一等奖');
                $form->text('point_second', '积分分值二等奖');
                $form->text('point_third', '积分分值三等奖');
            })
            ->when('=', mGoodsRecommender::TYPE_GOODS, function ($form) {
                $form->imgUpload('goods_pic_id', '商品图片', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
                $form->text('goods_price', '商品价值');
            });
        $form->text('activity_desc', '奖励简述')->required();

        $form->table('join_type', '参与方式', function ($table) {
            $table->text('desc', '参与方式');
        });
        $form->table('content_range', '内容范围', function ($table) {
            $table->text('desc', '内容范围');
        });
        $form->table('word_require', '文字要求', function ($table) {
            $table->text('desc', '文字要求');
        });
        $form->table('pic_require', '图片要求', function ($table) {
            $table->text('desc', '图片要求');
        });
        $form->table('goods_relation', '商品关联', function ($table) {
            $table->text('desc', '商品关联');
        });
        $form->userProfile('user_profile', '用户分群')->options()->generate();
        $form->linkSelect('link', '活动链接');
        $form->action('/admin/communityMcn/recommenderInfo/save');
        return $content
            ->header('创建好物官')
            ->breadcrumb(['text' => 'MCN项目管理', 'url' => ''], ['text' => '创建好物官'])
            ->row($form->render());
    }

    public static function save(Request $request)
    {
        $param = $request->all();
        $data = array();
        $data['title'] = $param['title'];
        $data['pic_id'] = $param['pic_id'];
        $data['activity_desc'] = $param['activity_desc'];
        $data['link_type'] = $param['link_type'];
        $data['link_params'] = json_encode($param['link_params'], JSON_UNESCAPED_UNICODE);
        $data['activity_tag'] = $param['activity_tag'][0] == '#'? $param['activity_tag']:'#'.$param['activity_tag'];
        $data['reward_type'] = $param['reward_type'];
        if ($data['reward_type'] == mGoodsRecommender::TYPE_POINT) {
            $pointList = [
                1 => $param['point_first'],
                2 => $param['point_second'],
                3 => $param['point_third'],
            ];
            $data['point_list'] = json_encode($pointList);
        } elseif ($data['reward_type'] == mGoodsRecommender::TYPE_GOODS) {
            $data['goods_pic_id'] = $param['goods_pic_id'];
            if(!$param['goods_price']){
                throw new InputErrorException('请输入商品价值', InputErrorException::DEFAULT_CODE, 'goods_price');
            }
            $data['goods_price'] = $param['goods_price'] * 100;
        }
        $contentList = [];

        foreach (self::CONTENT_PARAM_LIST as $key => $title) {
            if ($param[$key]) {
                $contentData = array_values($param[$key]);
                $descList = [];
                foreach ($contentData as $descs) {
                    $descList[] = $descs['desc'];
                }
                $contentList[] = [
                    'title' => $title,
                    'desc' => $descList
                ];
            }
        }

        $data['content'] = json_encode($contentList);
        $data['start_time'] = strtotime($param['start_time']);
        $data['end_time'] = strtotime($param['end_time']) + 24 * 60 * 60 - 1;
        if ($param['id']) {
            $result = mGoodsRecommender::updateData($param['id'], $data);
            AdmOperationModule::addUserProfile($param['id'], $param['user_profile'], PositionRules::MODULE_TYPE_RECOMMENDER);
        } else {
            $result = mGoodsRecommender::addData($data);
            AdmOperationModule::addUserProfile($result, $param['user_profile'], PositionRules::MODULE_TYPE_RECOMMENDER);
        }
        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/communityMcn/recommenderInfo/index')->with(compact('success'));
        }

    }


    private static function formatInfo($info){
        $info['start_time'] = date('Y-m-d',$info['start_time']);
        $info['end_time'] = date('Y-m-d',$info['end_time']);
        $info['goods_price'] = $info['goods_price']/100;
        if($info['reward_type'] == mGoodsRecommender::TYPE_POINT){
            $pointList = json_decode($info['point_list'],true);
            $info['point_first'] = $pointList[1];
            $info['point_second'] = $pointList[2];
            $info['point_third'] = $pointList[3];
        }
        if($info['content']){
            $contentList = json_decode($info['content'],true);
            foreach ($contentList as $value){
                $keyName = array_search($value['title'],self::CONTENT_PARAM_LIST);
                foreach($value['desc'] as $key => $value){
                    $info[$keyName]['new_'.($key + 1)]['desc'] = $value;
                    $info[$keyName]['new_'.($key + 1)]['_remove_'] = 0;
                }
            }
        }
        if($info['link_type']){
            $info['link'] = [
                "link_type" => $info['link_type'],
                "link_params" => json_decode($info['link_params'],1)
            ];
        }
        return $info;
    }
}